package com.mzy.linear_struct.hot100.二叉树;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: mizy3
 * @Date: 2024/08/10/下午7:31
 * @Description:
 */
public class Pro102二叉树的层序遍历 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();

        deque.offer(root);

        List<List<Integer>> ans = new ArrayList<>();
        while (!deque.isEmpty()) {
            int n = deque.size();
            ArrayList<Integer> list = new ArrayList<>();
            while (n-- > 0) {
                TreeNode node = deque.poll();
                list.add(node.val);

                if (node.left != null) {
                    deque.offer(node.left);
                }
                if (node.right != null) {
                    deque.offer(node.right);
                }
            }

            ans.add(list);
        }
        return ans;
    }
}
